package com.hengpeng.itfinoss.controller.activity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.en.ActivityStatus;
import com.hengpeng.itfinbase.en.ActivityType;
import com.hengpeng.itfinbase.en.CustomerType;
import com.hengpeng.itfinbase.en.PlatForm;
import com.hengpeng.itfinbase.persist.Activity;
import com.hengpeng.itfinbase.persist.Reward;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.controller.util.PageHandlerUtil;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.hengpeng.itfinoss.util.CollectionHelp;

/**
 * 活动奖品
 * 
 * @author liyangyang
 *
 */
@Controller
@RequestMapping(value = "/activity")
public class ActivityController extends BaseController {
    @Autowired
    private ServiceFactory serviceFactory;

    private String jspPath(String pageName) {

        return "activity/" + pageName;
    }

    @RequestMapping(value = "/load/{id}")
    public String ossConfig(ModelMap map, HttpServletRequest request, @PathVariable Long id) {
        Activity activity = serviceFactory.getPersistService().get(Activity.class, id);
        map.put("activity", activity);
        // 当前用户已经存在的角色
        Set<Reward> roleSet = null;

        // 当前用户已经存在的角色
        DynamicQuery query = new DynamicQuery(Reward.class);
        query.setQueryType(QueryType.JDBC);
        List<Reward> rewardListAll = serviceFactory.getPersistService().find(Reward.class, query);
        // 角色及系统组差异值集合
        Collection<Reward> roleListDiff = CollectionHelp.findCollectionDiff(rewardListAll, roleSet);
        map.put("rewardListAll", roleListDiff);
        return jspPath("/detail");
    }

    @RequestMapping(value = "/list")
    public String list(HttpServletRequest request, ModelMap map) {

        Pagination page = new Pagination(request);
        page.setPageSize(this.getPageSize(request));
        try {
            List<Activity> list = new ArrayList<Activity>();
            ServiceResult<List<Activity>> result = serviceFactory.getActivityService().selectActivityPage(
                    page.currentPage, page.pageSize);
            page.setEntityCount(result.getReturnListSize());
            list = result.getReturnValue();
            map.put("activityList", list);
            map.put("activityListPage", page);
            return "/activity/list";
        } catch (Exception ex) {
            ex.printStackTrace();
            return returnError(map, ex);
        }
    }

    @RequestMapping(value = "/update")
    public String update(HttpServletRequest request, Long[] rewards, ModelMap map, Long id, String activityName,
            ActivityStatus status, CustomerType customerType, PlatForm platform, Date startDate, Date endDate,
            ActivityType activityType) {
        try {
            Set<Reward> rewardSet = new HashSet<Reward>();
            if (rewards != null && rewards.length > 0) {

                List<Reward> rewardList = serviceFactory.getActivityService().findRewardByIds(rewards);
                if (rewardList == null || rewardList.size() <= 0 || rewardList.size() != rewards.length) {
                    return PageHandlerUtil.returnError(map, "您选中的奖品已经不存在，请刷新页面后重试！");
                }
                rewardSet = new HashSet<Reward>(rewardList);
            }

            serviceFactory.getActivityService().modify(id, activityName, status, customerType, platform, startDate,
                    endDate, activityType, rewardSet);
        } catch (Exception e) {
            e.printStackTrace();
            return PageHandlerUtil.returnError(map, e);
        }
        return PageHandlerUtil.returnSuccess(map, "/activity/list");
    }

    @RequestMapping(value = "/create")
    public String initSave(ModelMap map) {
        List<Reward> rewardList = serviceFactory.getPersistService().list(Reward.class);
        map.put("activity", new Activity());
        map.put("rewardList", rewardList);
        return "activity/create";
    }

    @RequestMapping(value = "/onsave")
    public String save(@ModelAttribute Activity activity, ModelMap map, HttpSession session) {
        try {
            // 校验数据无误，进入持久化操作
            serviceFactory.getActivityService().save(activity);
            return PageHandlerUtil.returnSuccess(map, "/activity/list");
        } catch (Exception ex) {
            ex.printStackTrace();
            return PageHandlerUtil.returnError(map, ex);
        }
    }

}
